package com.swd.order.controller;


import com.swd.order.vo.Ret;
import com.swd.order.vo.Rets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {

    @Value("${upload}")
    private String uploadPath;

    @PostMapping("img/upload")
    public Ret upload(MultipartFile img)  {

        String newFileName = UUID.randomUUID().toString()+".jpg";

        try {
            String name = img.getOriginalFilename();
            if (!(name.endsWith(".jpg") || name.endsWith(".png"))){
              throw new Exception("请上传图片");
            }

            img.transferTo(new File(uploadPath+newFileName));

        } catch (Exception e) {
            return Rets.failure(e.getMessage());
        }
        return Rets.success(newFileName);
    }

    @RequestMapping("img/{name}")
    public void getImage(@PathVariable String name, HttpServletResponse response){
        try {
            File file = new File(uploadPath+name+".jpg");
            byte[] bytes = FileCopyUtils.copyToByteArray(file);
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
//            return Rets.failure(e.getMessage());
        }
//        return Rets.success();
    }

}
